<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible" :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="设备号" prop="equipmentNum">
            <el-input v-model="form.equipmentNum" placeholder="请输入设备号" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="车牌号" prop="carId">
            <el-input v-model="form.carId" placeholder="请输入车牌号" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="运行方向" prop="carNum">
            <el-input v-model="form.carNum" placeholder="请输入运行方向" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="司机姓名" prop="personName">
            <el-input v-model="form.personName" placeholder="请输入司机姓名" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="司机手机号" prop="phonenum">
            <el-input v-model="form.phonenum" placeholder="请输入司机手机号" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="归属公司" prop="belongId">
            <el-input v-model="form.belongId" placeholder="请输入归属公司" />
          </el-form-item>
        </el-col>
        <el-divider content-position="center">站点(子)信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddOrderItem">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteOrderItem">删除</el-button>
          </el-col>
        </el-row>
        <el-table ref="OrderItem" :data="carStationList" :row-class-name="rowOrderItemIndex" tooltip-effect="dark"
          style="width: 100%" @selection-change="handleOrderItemSelectionChange">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column label="车次" prop="state">
            <template #default="scope">
              <el-select v-model="scope.row.state" placeholder="请选择车次" clearable size="small">
                <el-option v-for="dict in tqcStateOptions" :key="dict.id" :label="dict.label" :value="dict.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="站点" prop="stationId">
            <template #default="scope">
              <el-select v-model="scope.row.stationId" clearable filterable remote @focus="changeVal()"
                :remote-method="remoteMethod" placeholder="请选择站点">
                <el-option v-for="item in staoptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="到站时间" prop="arrivalTime">
            <template #default="scope">
              <el-time-picker v-model="scope.row.arrivalTime" value-format="HH:mm:ss"
                placeholder="请选择时间点"></el-time-picker>
            </template>
          </el-table-column>
          <el-table-column label="排序" prop="sort">
            <template #default="scope">
              <el-input v-model="scope.row.sort" placeholder="请输入排序" style="width: 100px" />
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="CarBasicDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj, stationListQuery, carlist } from '/@/api/newtqc/carbasic'
import { rule } from '/@/utils/validate';
import { remote } from '/@/api/admin/dict';
const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
// 定义字典


//站点添加
const carStationList = ref([]);
const checkedOrderItem = ref([]);
const tqcStateOptions = ref([{
  id: 1,
  label: '车次一',
  value: 1
}]);
const staoptions = ref([]);
// 提交表单数据
const form = reactive({
  id: 0,
  equipmentNum: '',
  carId: '',
  carNum: '',
  personName: '',
  phonenum: '',
  belongId: '',
  carStationList: []
});

// 定义校验规则
const dataRules = ref({
})

// 打开弹窗
const openDialog = (id: number) => {
  visible.value = true
  form.id = 0

  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });

  // 获取carBasic信息
  if (id > 0) {
    form.id = id
    getcarBasicData(id)
  } else {
    carStationList.value = []
  }
  // dictList()
};
const changeVal = () => {
  staoptions.value = []

}
//远程搜索
const remoteMethod = (query: any) => {
  console.log('query', query)
  let name = { name: query }
  stationListQuery(name).then((response) => {
    let searchData = response.data
    staoptions.value = searchData.map((item: any) => {
      return { value: `${item}`, label: `${item}` }
    })
  })
}
// 字典
const dictList = () => {
  let type = 'tqc_bc'
  remote(type).then((response) => {
    tqcStateOptions.value = response.data.data
    console.log('33333', tqcStateOptions)
  })
}
/** (子)序号 */
const rowOrderItemIndex = ({ row, rowIndex }) => {
  row.index = rowIndex + 1
}
/** 单选框选中数据 */
const handleOrderItemSelectionChange = (selection: any) => {
  checkedOrderItem.value = selection
}
/** (子)添加按钮操作 */
const handleAddOrderItem = () => {
  let obj = {
    stationId: '',
    state: '',
    arrivalTime: ''
  }

  carStationList.value.push(obj)
}
/** 预约(子)删除按钮操作 */
const handleDeleteOrderItem = () => {
  if (checkedOrderItem.value.length == 0) {
    // .alert('请先选择要删除(子)数据', '提示', {
    //   confirmButtonText: '确定'
    // })
  } else {
    checkedOrderItem.value.forEach((item: { index: any; }) => {
      for (let i = 0; i < carStationList.value.length; i++) {
        if (carStationList.value[i].index === item.index) {
          carStationList.value.splice(i, 1)
          break
        }
      }
    })
    checkedOrderItem.value = []
  }
}
// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => { });
  if (!valid) return false;
  console.log('form', form);
  form.carStationList = carStationList
  try {
    loading.value = true;
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};


// 初始化表单数据
const getcarBasicData = (id: number) => {
  // 获取数据
  loading.value = true
  getObj(id).then((res: any) => {
    Object.assign(form, res.data)
    let carId = form.carId
    carlist(carId).then((response) => {
      carStationList.value = response.data
    })
  }).finally(() => {
    loading.value = false
  })
};

// 暴露变量
defineExpose({
  openDialog
});
</script>